package com.zpkj.portal.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.zpkj.portal.dto.ResponseParameter;
import com.zpkj.portal.exception.ServiceException;
import com.zpkj.portal.utils.Constant;

/**
 * 程序异常拦截处理
 * 
 * @author admin
 */
@ControllerAdvice
class CustomMappingExceptionResolver extends SimpleMappingExceptionResolver {
	public static final String DEFAULT_ERROR_VIEW = "error";

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		ResponseParameter result = new ResponseParameter();
		String requestSource = request.getParameter("requestSource");
		result.setRequestSource(requestSource);
		// 组装输出内容
		if (ex instanceof ServiceException) {
			String errorCode = StringUtils.isEmpty(ex.getMessage()) ? Constant.ReturnCode.CODE_1110 : ex.getMessage();
			String message = Constant.ReturnCodeInfoMap.get(errorCode);
			if (StringUtils.isEmpty(message)) {
				errorCode = Constant.ReturnCode.CODE_1110;
				message = ex.getMessage();
			}
			result.addError(errorCode, message);
			// 打印异常
			/* ex.printStackTrace(); */
		} else {
			result.addError(Constant.ReturnCode.CODE_0000, ex.getMessage());
			// 打印异常
			ex.printStackTrace();
		}
		// 返回终端
		HandlerMethod mathod = (HandlerMethod) handler;
		ResponseBody body = mathod.getMethodAnnotation(ResponseBody.class);
		// 判断有没有@ResponseBody的注解没有的话调用父方法
		if (body == null) {
			ModelAndView mav = new ModelAndView();
			mav.addObject("exception", ex);
			mav.addObject("url", request.getRequestURL());
			mav.setViewName(DEFAULT_ERROR_VIEW);
			return mav;
		}
		// 使用view视图返回方式
		ModelAndView mv = new ModelAndView();
		// MappingJackson2JsonView view = new MappingJackson2JsonView();
		// Map<String, Object> attributes = new HashMap<String, Object>();
		// attributes = new Gson().fromJson(result.toJson(), new TypeToken<Map<String,
		// Object>>(){}.getType());
		// view.setAttributesMap(attributes);
		JsonView view = new JsonView();
		Map<String, Object> attributes = new HashMap<String, Object>();
		attributes.put("result", result.toJson());
		view.setAttributesMap(attributes);
		mv.setView(view);
		return mv;
	}
}
